import type { HarData, ParsedEntry } from '../types/har';
import { ResourceType, CacheStatus } from '../types/har';

/**
 * 从 URL 中提取域名
 */
function extractDomain(url: string): string {
  try {
    return new URL(url).hostname;
  } catch {
    return 'unknown';
  }
}

/**
 * 根据 MIME 类型确定资源类型
 */
function getResourceType(mimeType: string): ResourceType {
  if (mimeType.includes('text/html')) return ResourceType.DOCUMENT;
  if (mimeType.includes('text/css')) return ResourceType.STYLESHEET;
  if (mimeType.includes('image/')) return ResourceType.IMAGE;
  if (mimeType.includes('video/') || mimeType.includes('audio/')) return ResourceType.MEDIA;
  if (mimeType.includes('font/') || mimeType.includes('application/font')) return ResourceType.FONT;
  if (mimeType.includes('application/javascript') || mimeType.includes('text/javascript')) return ResourceType.SCRIPT;
  if (mimeType.includes('application/json') || mimeType.includes('text/xml')) return ResourceType.XHR;
  if (mimeType.includes('application/manifest+json')) return ResourceType.MANIFEST;
  return ResourceType.OTHER;
}

/**
 * 确定缓存状态
 */
function getCacheStatus(entry: any): CacheStatus {
  const cache = entry.cache;
  if (!cache) return CacheStatus.UNKNOWN;
  
  if (cache.beforeRequest?.hitCount > 0) return CacheStatus.HIT;
  if (cache.afterRequest?.hitCount > 0) return CacheStatus.PARTIAL;
  return CacheStatus.MISS;
}

/**
 * 解析 HAR 文件中的数据为结构化对象
 */
export function parseHar(har: HarData): ParsedEntry[] {
  if (!har?.log?.entries) {
    throw new Error('Invalid HAR file format');
  }

  return har.log.entries.map((entry) => {
    const url = entry.request.url;
    const domain = extractDomain(url);
    const mimeType = entry.response.content.mimeType || '';
    const resourceType = getResourceType(mimeType);
    const cacheStatus = getCacheStatus(entry);
    
    // 计算各种时间指标
    const timings = entry.timings || {};
    const totalTime = entry.time || 0;
    
    return {
      url,
      method: entry.request.method,
      status: entry.response.status,
      contentType: mimeType,
      size: entry.response.bodySize || 0,
      time: totalTime,
      domain,
      resourceType,
      timings: {
        dns: timings.dns || 0,
        connect: timings.connect || 0,
        ssl: timings.ssl || 0,
        send: timings.send || 0,
        wait: timings.wait || 0,
        receive: timings.receive || 0,
        total: totalTime
      },
      cacheStatus
    };
  });
}

/**
 * 兼容旧版本的函数名
 * @deprecated 请使用 parseHar 替代
 */
export const dealHar = parseHar;

/**
 * 验证 HAR 文件格式
 */
export function validateHarFile(har: any): boolean {
  try {
    return !!(
      har &&
      har.log &&
      Array.isArray(har.log.entries) &&
      har.log.entries.length > 0 &&
      har.log.entries[0].request &&
      har.log.entries[0].response
    );
  } catch {
    return false;
  }
}

/**
 * 获取 HAR 文件的基本信息
 */
export function getHarFileInfo(har: HarData) {
  const entries = har.log.entries || [];
  const totalRequests = entries.length;
  const totalSize = entries.reduce((sum, entry) => sum + (entry.response.bodySize || 0), 0);
  const totalTime = Math.max(...entries.map(entry => entry.time || 0));
  
  return {
    version: har.log.version,
    creator: har.log.creator,
    totalRequests,
    totalSize,
    totalTime,
    startTime: (entries[0] as any)?.startedDateTime || null,
    endTime: (entries[entries.length - 1] as any)?.startedDateTime || null
  };
}
